package com.ccnu.sm.aop;/*
 * @author raohj
 * @date 2019/12/1120:20
 * @description add your comment
 */
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.aop.AfterAdvice;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/*
* 功能描述
* @author raohj
* @date 2019/12/19
* @descript 通知，
* @params
* @return
*/

@Component
@Aspect
public class RAOPAnnotation implements MethodBeforeAdvice, AfterReturningAdvice , ThrowsAdvice, AfterAdvice {
    private static final Log log = LogFactory.getLog(RAOPAnnotation.class);
    private long startTime = 0L;
    /*
    * 功能描述
    * @author raohj
    * @date 2019/12/11
    * @descript 执行方法前的切面
    * @params
    * @return
    */
    @Override
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        startTime = System.nanoTime();
    }

//    @Before(value = "execution(public * *(..))")
    @Before(value = "within(com.ccnu.sm.aop.*)")
    public void before(JoinPoint jp){
        log.debug("调用before");
        startTime = System.nanoTime();
    }

    @After(value = "within(com.ccnu.sm.aop.*)")
    public void after(JoinPoint jp){
        log.debug("after");
    }

    @AfterReturning(value = "within(com.ccnu.sm.aop.*)")
    public void afterReturning(JoinPoint jp){
        log.debug("afterReturning");
    }

    @AfterThrowing(value = "execution(public * *(..))", throwing = "t")
    public void afterThrowing(JoinPoint jp, Throwable t){
        log.debug("afterThrowing");
    }

    /*
    * 功能描述
    * @author raohj
    * @date 2019/12/11
    * @descript 执行方法后的切面
    * @params
    * @return
    */
    @Override
    public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
        long elaspedTime = System.nanoTime() - startTime;
        String className = o1.getClass().getCanonicalName();
        String methodName = method.getName();
        log.debug("执行" + className + ":" + methodName + "耗时：" + elaspedTime);
    }

    /*
    * 功能描述
    * @author raohj
    * @date 2019/12/18
    * @descript 抛出异常前，先进行捕获处理
    * @params 
    * @return 
    */
    public void afterThrowing(Method method, Object[] args, Object target, Exception ex){
        log.debug("Execution of" + target.getClass().getName() + "#" + method.getName() + "end with exception:" + ex.getMessage());
    }
}
